#!/usr/bin/node

// const base64 = process.argv[2];
// console.log(base64);

// const buf = Buffer.from(base64, 'base64');

// console.log(buf.toString('utf8'));
// let msg = buf.toString('utf8');
// console.log(msg);

// msg = msg.split(':');
// msg = { userName: msg[0], passWord: msg[1] };
// console.log(msg);

//网课部分
//Buffer对字符串的编码转换
// let msg = process.argv[2];

// //basic解码
// let parseBasicAuth = function (encodeString) {
//   let buf = new Buffer(encodeString, 'base64');
//   let parts = buf.toString('utf8').split(':');

//   return {
//     userName: parts[0],
//     passWord: parts[1]
//   };
// };

// let credentials = parseBasicAuth(msg);

// console.log(credentials);
// 引入 Node.js 的 Buffer 模块
const { Buffer } = require('buffer');

// 检查命令行参数的数量
if (process.argv.length !== 3) {
  console.error('Usage: node script.js <base64_string>');
  process.exit(1); // 参数不正确时，以退出码 1 退出
}

// 获取命令行参数中的 base64 编码字符串
let msg = process.argv[2];

// 基本解码函数
let parseBasicAuth = function (encodeString) {
  try {
    let buf = Buffer.from(encodeString, 'base64');
    let parts = buf.toString('utf8').split(':');
    if (parts.length !== 2) {
      throw new Error('Invalid credentials format');
    }
    return {
      userName: parts[0],
      passWord: parts[1]
    };
  } catch (error) {
    console.error('Error: Invalid base64 string or credentials format.');
    process.exit(1);
  }
};

// 解码 base64 编码的字符串（方式一）
let credentials = parseBasicAuth(msg);

// 打印还原后的用户名和密码信息
console.log('Decoded credentials:', credentials);

// 解码 base64 编码的字符串（方式二）
let alternativeDecode = function (encodeString) {
  try {
    let credentials = parseBasicAuth(encodeString);
    return credentials;
  } catch (error) {
    console.error('Error: Invalid base64 string or credentials format.');
    process.exit(1);
  }
};

// 使用第二种方式解码并打印
let alternativeCredentials = alternativeDecode(msg);
console.log('Alternative decoded credentials:', alternativeCredentials);

